#include <iostream>
using namespace std;
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <cstring>

#define SIZE 4096

void test1(string &filename)
{
    int fd = ::open(filename.c_str(),O_RDONLY);
    if (fd < 0)
    {
        std::cerr << "open error" << std::endl;
    }

    // 根据文件描述符 获取文件真实大小
    struct stat st;
    ::fstat(fd,&st);

    char *mmap_addr = (char *)::mmap(nullptr, st.st_size, PROT_READ, MAP_SHARED, fd, 0);
    if (mmap_addr == MAP_FAILED)
    {
        perror("mmap");
    }

    cout<<mmap_addr<<endl;

    ::munmap(mmap_addr, SIZE);
    ::close(fd);
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        std::cerr << "Usage: " << argv[0] << " filename" << std::endl;
        return 1;
    }

    string filename = argv[1];
    test1(filename);
}